package userservicelogic

import (
	"context"
	"smile-sunshine-micorservice/rpc/User/db/crud"
	"smile-sunshine-micorservice/rpc/User/internal/svc"
	"smile-sunshine-micorservice/rpc/User/internal/utils/password"
	"smile-sunshine-micorservice/rpc/User/pb/zipTako.com/SmileSunshine/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	UsersModel crud.UsersModel
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:        ctx,
		svcCtx:     svcCtx,
		Logger:     logx.WithContext(ctx),
		UsersModel: crud.NewUsersModel(svcCtx.SqlConn, svcCtx.CacheConf),
	}
}

func (l *LoginLogic) Login(in *user.LoginRequest) (*user.LoginResponse, error) {
	l.Logger.Infof("收到登录请求, Email: %s", in.Email)

	// 1. 参数验证
	if len(in.Email) == 0 || len(in.Password) == 0 {
		return &user.LoginResponse{
			Success: false,
			Message: "用户名或密码不能为空",
		}, nil
	}

	// 2. 查询用户
	userInfo, err := l.UsersModel.FindOneByEmail(l.ctx, in.Email)
	if err != nil {
		l.Logger.Errorf("查询用户失败：%v", err)
		return &user.LoginResponse{
			Success: false,
			Message: "邮箱或密码错误",
		}, nil
	}

	// 3. 验证密码
	if !password.ComparePasswords(userInfo.HashPassword, in.Password) {
		l.Logger.Info("密码验证失败")
		return &user.LoginResponse{
			Success: false,
			Message: "用户名或密码错误",
		}, nil
	}

	// 4. 返回成功响应
	return &user.LoginResponse{
		Success: true,
		Message: "登录成功",
		UserId:  userInfo.Id,
	}, nil
}
